package com.example.lib_audio.audio

import android.util.Log
import com.example.lib_audio.eventbus.AudioChangeProgressEvent
import com.example.lib_audio.eventbus.AudioLoadEvent
import com.example.lib_audio.eventbus.AudioPauseEvent
import com.example.lib_audio.eventbus.AudioRestartRotateAnim
import com.example.lib_audio.eventbus.AudioStartEvent
import com.example.lib_base.model.Song
import com.example.lib_ui_base.WjbTimeUtil
import org.greenrobot.eventbus.EventBus

class AudioPlayer {
    private val mPlayer = StateMediaPlayer()
    private  var timer:WjbTimeUtil? = null
    private lateinit var currentSong:Song


    //加载音乐
    fun loadMusic(song:Song){
        mPlayer.reset()
        mPlayer.setDataSource(song.url)
        mPlayer.prepareAsync()
        currentSong = song
        mPlayer.setOnPreparedListener {
            start()
        }
        //发送事件
        EventBus.getDefault().post(AudioLoadEvent(currentSong))

    }

    //播放
    fun start(){
        if (mPlayer.getStatus() == StateMediaPlayer.MediaPlayerState.PREPARED || mPlayer.getStatus() == StateMediaPlayer.MediaPlayerState.PAUSE){
            mPlayer.start()
            initTimer()//更新进度
            EventBus.getDefault().post(AudioStartEvent)
        }
    }


    //重新播放
    fun replay(){
        mPlayer.seekTo(0)
        EventBus.getDefault().post(AudioRestartRotateAnim)
    }

    private fun initTimer(){
        timer = WjbTimeUtil()
            .setInterval(200)
            .setOrder(WjbTimeUtil.Order.NONE)
            .setCallback { wjbTimeUtil, i ->
                EventBus.getDefault().post(AudioChangeProgressEvent(getCurrentProgress(),getSongDuration()))
            }
        timer?.start()
    }

    fun stopTimer(){
        timer?.stop()
        timer = null
    }

    //暂停
    fun pause(){
        if(mPlayer.getStatus() == StateMediaPlayer.MediaPlayerState.START){
            mPlayer.pause()
            stopTimer()
            EventBus.getDefault().post(AudioPauseEvent)
        }
    }

    //停止
    fun stop(){

        mPlayer.stop()
    }

    //是否正在播放
    fun isPlaying() = mPlayer.isPlaying


    //恢复播放
    fun resume(){
        start()
    }

    //释放 程序退出时
    fun release(){
        mPlayer.release()
    }

    //监听播放完毕事件
    fun addCompletionListener(callback:()->Unit){
        mPlayer.setOnCompletionListener {
            callback()
        }
    }

    //获取歌曲的总时长
    fun getSongDuration() = mPlayer.duration


    //获取当前播放的进度
    fun getCurrentProgress() = mPlayer.currentPosition


}